package cn.edu.zafu.bigdata.mahuilin;

import java.io.*;
import java.net.*;

public class TimeServer {
    public static void main(String[] args) throws IOException {
        int port = 1234; // 服务端监听的端口号
        System.out.println("Time server running on port " + port);

        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            while (true) {
                byte[] receiveData = new byte[1024];
                byte[] sendData = new byte[1024];

                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);

                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Client says: " + sentence);

                String currentTime = new java.util.Date(java.util.Calendar.getInstance().getTimeInMillis()) + "";
                String output = "Server Time: " + currentTime;
                System.out.println("Server response: " + output);

                sendData = output.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            System.out.println("Server exception: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
